package ouhenry.stage.manage.service;

import java.io.Serializable;
import java.time.LocalDateTime;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import ouhenry.stage.common.base.ErrorEnum;
import ouhenry.stage.common.base.Result;
import ouhenry.stage.common.config.SnowFlake;
import ouhenry.stage.manage.dao.UserDao;
import ouhenry.stage.manage.entity.User;
import ouhenry.stage.manage.form.UserForm;
import ouhenry.stage.manage.vo.UserLoginVo;

@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Resource
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    public Result<UserLoginVo> loginVerify(UserForm userForm) {
        User user = userDao.loginVerify(userForm.getUserName(), userForm.getPassword());
        if (user != null && user.getId() != null) {
            UserLoginVo login = new UserLoginVo();
            login.setUid(user.getId());
            login.setUserName(user.getUserName());
            login.setToken(user.getUserName());

            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            Object result = operations.get("user::" + user.getId());
            System.out.println(result);
            operations.set("user::" + user.getId(), JSONObject.toJSONString(login));

            return Result.success(login);
        }
        return Result.fail(ErrorEnum.ACCOUNT_NOT_EXIST);
    }

    public Result<UserLoginVo> add(UserForm userForm) {
        User insert = new User();
        insert.setId(SnowFlake.generateId());
        insert.setUserName(userForm.getUserName());
        insert.setCreateTime(LocalDateTime.now());
        insert.setPassword(userForm.getPassword());
        userDao.insert(insert);
        return Result.success(null);
    }

    @Transactional
    @CacheEvict(value = "user", key = "#userForm.userId", condition = "#userForm.userId!=null")
    public Result<UserLoginVo> update(UserForm userForm) {
        User update = new User();
        update.setId(userForm.getUserId());
        update.setUserName(userForm.getUserName());
        update.setUpdateTime(LocalDateTime.now());
        update.setPassword(userForm.getPassword());
        userDao.updateByPrimaryKeySelective(update);
        return Result.success(null);
    }

}
